﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Domain.Entities;
using Domain.UnitOfWork;
using Mestedur.Models;
using Mestedur.ViewModels;
using Mestedur.ViewModels.EditorViewModels;
using Services;

namespace Mestedur.Controllers
{
    public class EditorController : Controller
    {
        //
        // GET: /Editor/
        private IEditorService editorService;
        private IDatabaseService databaseService;
        private IUnitOfWorkFactory unitOfWorkFactory;


        public EditorController(IEditorService editorService,IDatabaseService databaseService,IUnitOfWorkFactory unitOfWorkFactory)
        {
            this.editorService = editorService;
            this.unitOfWorkFactory = unitOfWorkFactory;
            this.databaseService = databaseService;
        }
        public ActionResult Index()
        {
            using (unitOfWorkFactory.Create())
            {
                var courses = databaseService.Courses.GetAll();
                var viewModel = ViewModelConverter.ConvertCoursesToCourseViewModels(courses);
                return View(viewModel);
            }
        }
            
        public ActionResult StartCreation()
        {
            return View();
        }

        public ActionResult ViewQuestions(int id)
        {
            
            using (unitOfWorkFactory.Create())
            {
                Chapter chapter = databaseService.Chapters.Get(id);
                var questions = editorService.ViewQuestionForChapter(chapter);
                var viewModel = ConvertChapterToChapterViewModel(chapter, questions);
                return View(viewModel);
            } 
        }

        private ChapterViewModel ConvertChapterToChapterViewModel(Chapter chapter, IEnumerable<Question> questions)
        {
            var chapterViewModel = ViewModelConverter.ConvertChapterToChapterViewModel(chapter);
            chapterViewModel.Questions = ViewModelConverter.ConvertQuestionsToQuestionsViewModel(questions);
            return chapterViewModel;
        }


        public ActionResult EditCourse(int? id)
        {
            using (unitOfWorkFactory.Create())
            {
                var model = editorService.EditCourse(id)??new Course();
                EditorCourseViewModel viewModel = new EditorCourseViewModel
                                                      {Id = model.Id, CourseName = model.CourseName};
                return View(viewModel);
            }
        }

        [HttpPost]
        public ActionResult EditCourse(EditorCourseViewModel viewModel)
        {
            using (var unit = unitOfWorkFactory.Create())
            {
                editorService.SaveCourse(viewModel.Id, viewModel.CourseName, viewModel.NumberInOrder);
                unit.Commit();
                return Redirect("/Editor/Index");

            }
        }

        public ActionResult EditTopic(int? id)
        {
            using (unitOfWorkFactory.Create())
            {
                var model = editorService.EditTopic(id)??new Topic();
                int courseId = -1;
                if (model.Course != null) courseId = model.Course.Id;
                EditorTopicViewModel viewModel = new EditorTopicViewModel { Id = model.Id, CourseId = courseId, TopicName = model.TopicName };
                ViewBag.Courses = databaseService.Courses.GetAll();
                return View(viewModel);
            }
        }
        [HttpPost]
        public ActionResult EditTopic(EditorTopicViewModel viewModel)
        {
            using (var unit = unitOfWorkFactory.Create())
            {
                editorService.SaveTopic(viewModel.Id, viewModel.TopicName, viewModel.CourseId, viewModel.NumberInOrder);
                unit.Commit();
                return Redirect("/Editor/Index");

            }
        }

        public ActionResult EditChapter(int? id)
        {
            using (unitOfWorkFactory.Create())
            {
                var model = editorService.EditChapter(id)??new Chapter();
                int topicId = -1;
                if (model.Topic != null) topicId = model.Topic.Id;
                EditorChapterViewModel viewModel = new EditorChapterViewModel{Id = model.Id, ChapterData = model.ChapterData, ChapterName = model.ChapterName,TopicId = topicId };
                ViewBag.Topics = databaseService.Topics.GetAll();
                return View(viewModel);
            }
        }
        [ValidateInput(false)]
        [HttpPost]
         public ActionResult EditChapter(EditorChapterViewModel viewModel)
        {
            using (var unit = unitOfWorkFactory.Create())
            {
                editorService.SaveChapter(viewModel.Id, viewModel.ChapterName, viewModel.ChapterData, viewModel.TopicId, viewModel.NumberInOrder);
                unit.Commit();
                return Redirect("/Editor/Index");
            }
         
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult EditQuestion(int? id)
        {
            using (unitOfWorkFactory.Create())
            {
                var model = editorService.EditQuestion(id)??new Question();
                var answers = new List<EditorAnswerViewModel>();
                if (model.Answers != null)
                {
                    foreach (var answer in model.Answers)
                    {
                        answers.Add(new EditorAnswerViewModel
                                        {
                                            Id = answer.Id,
                                            AnswerText = answer.AnswerText,
                                            Correctness = answer.Correctness
                                        });
                    }
                }
                EditorQuestionViewModel viewModel = new EditorQuestionViewModel()
                                                        {
                                                            Id = model.Id,
                                                            QuestionMedia = model.MediaData,
                                                            Answers = answers
                                                        };
                viewModel.ChapterId = int.Parse(Request["ChapterId"] ?? "0");
                ViewBag.Chapters = databaseService.Chapters.GetAll();
                return View(viewModel);
            }
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult EditQuestion(FormCollection collection)
        {
            using (var unit = unitOfWorkFactory.Create())
            {
                int id;
                if (!int.TryParse(collection["id"] ?? "", out id))
                    id = -1;
                int chapterId;
                if (!int.TryParse(collection["ChapterId"] ?? "", out chapterId))
                    chapterId = -1;
                var answers = new List<Answer>();
                if (collection["QuestionType"].Equals("one"))
                {
                    answers.Add(new Answer()
                                    {
                                        AnswerText = collection["textanswer"],
                                        Correctness = true,
                                    });
                }
                else
                    if (collection.AllKeys.Contains("Answers"))
                    {
                        for (int i = 0; i < collection.GetValues("Answers").Count(); i++)
                        {
                            int specialId = int.Parse(collection.GetValues("AnswerID")[i]);
                            answers.Add(new Answer()
                                            {
                                                AnswerText = collection.GetValues("Answers")[i],
                                                Correctness = collection.GetValues("AnswerRight") != null ?
                                                    collection.GetValues("AnswerRight").Any(x => x.Equals(specialId.ToString())) :
                                                    false
                                            });
                        }
                    }
                if (answers.Count > 0 && answers.Any(x => x.Correctness))
                    editorService.SaveQuestion(id, collection["QuestionMedia"], chapterId, answers);
                unit.Commit();
                if (chapterId > 0)
                    return Redirect("/Editor/ViewQuestions/" + chapterId);
                else
                    return Redirect("/Editor/Index");
            }
            
        }

        public ActionResult DeleteChapter(int id)
        {
            using (unitOfWorkFactory.Create())
            {
                var chapter = databaseService.Chapters.Get(id);
                var viewModel = ViewModelConverter.ConvertChapterToChapterViewModel(chapter);
                return View(viewModel);
            }
        }

        public ActionResult AcceptChapterDeletion(int id)
        {
            using (var unit = unitOfWorkFactory.Create())
            {
                var chapter = databaseService.Chapters.Get(id);
                databaseService.Chapters.Delete(chapter);
                unit.Commit();
                return Redirect("/Editor/Index");
            }
            
        }


        public ActionResult DeleteTopic(int id)
        {
            using (unitOfWorkFactory.Create())
            {
                var topic = databaseService.Topics.Get(id);
                var viewModel = ViewModelConverter.ConvertTopicToTopicViewModel(topic);
                return View(viewModel);
            }
        }

        public ActionResult AcceptTopicDeletion(int id)
        {
            using (var unit = unitOfWorkFactory.Create())
            {
                var topic =  databaseService.Topics.Get(id);
                databaseService.Topics.Delete(topic);
                unit.Commit();
                return Redirect("/Editor/Index");
            }

        }

        public ActionResult DeleteCourse(int id)
        {
            using (unitOfWorkFactory.Create())
            {
                var course = databaseService.Courses.Get(id);
                var viewModel = ViewModelConverter.ConvertCourseToCourseViewModel(course);
                return View(viewModel);
            }
        }

        public ActionResult AcceptCourseDeletion(int id)
        {
            using (var unit = unitOfWorkFactory.Create())
            {
                var course = databaseService.Courses.Get(id);
                databaseService.Courses.Delete(course);
                unit.Commit();
                return Redirect("/Editor/Index");
            }

        }
    }
}
